package com.atguigu.jinx.conf;

import com.atguigu.jinx.entity.dto.User;
import com.atguigu.jinx.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class LogoutService implements LogoutHandler {

    private final UserMapper userDao;

    @Override
    public void logout(
            HttpServletRequest request,
            HttpServletResponse response,
            Authentication authentication
    ) {
        final String authHeader = request.getHeader("Authorization");
        final String jwt;
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            return;
        }
        jwt = authHeader.substring(7);
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        var user = userDao.selectOne(wrapper.eq(User::getToken, jwt));
        if (user != null) {
            user.setTokenExpired(true);
            userDao.updateById(user);
            SecurityContextHolder.clearContext();
        }
    }
}
